import { Button, message, Popconfirm, Switch, Table, Image, FormInstance } from "antd";
import { ColumnProps } from "antd/lib/table";
import {
	Dispatch,
	forwardRef,
	ForwardRefRenderFunction,
	MutableRefObject,
	RefObject,
	SetStateAction,
	useCallback,
	useContext,
	useImperativeHandle,
	useMemo,
	useRef,
	useState,
} from "react";
import { deleteSource, updateSource } from "src/api";
import { ImgUploadRef } from "src/components/dataEntry/ImgUpload";
import EllipsisText from "@/components/dataPresentation/EllipsisText";
import { AppContext } from "src/providers";
import { getDateColumns } from "src/util";
import { RoleRecord } from "../RoleType";

interface RoleListProps {
	list: RoleRecord[];
	fetchList: () => Promise<unknown>;
	operatedRecord: MutableRefObject<RoleRecord | null>;
	setMode: Dispatch<SetStateAction<"edit" | "find" | "add">>;
	setInfoVisible: Dispatch<SetStateAction<boolean>>;
	setAuthVisible: Dispatch<SetStateAction<boolean>>;
	formRef: MutableRefObject<FormInstance | null>;
	uploadRef: RefObject<ImgUploadRef>;
}
export interface RoleListRef {
	setTotal: (total: number) => void;
	getPageInfo: () => { current: number; pageSize: number };
}
const RoleList: ForwardRefRenderFunction<RoleListRef, RoleListProps> = (
	{ list, fetchList, operatedRecord, setMode, setInfoVisible, setAuthVisible, formRef, uploadRef },
	ref
) => {
	useImperativeHandle(ref, () => ({
		setTotal(total) {
			setRolePageOptions({ current: rolePageRef.current, pageSize: rolePageSizeRef.current, total });
		},
		getPageInfo() {
			return {
				current: rolePageRef.current,
				pageSize: rolePageSizeRef.current,
			};
		},
	}));
	const { REACT_APP_BASEURL } = useContext(AppContext);
	const rolePageRef = useRef(1);
	const rolePageSizeRef = useRef(10);
	const [rolePageOptions, setRolePageOptions] = useState({ current: rolePageRef.current, pageSize: rolePageSizeRef.current, total: 0 });
	const [loadingList, setLoadingList] = useState<string[]>([]);
	const loadingListRef = useRef<string[]>([]);
	const deleteLoadingItem = useCallback(
		(id: string) => {
			loadingListRef.current.forEach((item, index) => {
				if (item === id) loadingListRef.current.splice(index, 1);
			});
			setLoadingList([...loadingListRef.current]);
		},
		[loadingList]
	);
	const roleColumns = useMemo<ColumnProps<RoleRecord>[]>(
		() => [
			// {
			// 	title: "ID",
			// 	dataIndex: "_id",
			// 	width: 4,
			// },
			{
				title: "名称",
				dataIndex: "name",
				width: 10,
			},
			{
				title: "描述",
				dataIndex: "description",
				width: 10,
				render: text => <EllipsisText>{text}</EllipsisText>,
			},
			{
				title: "状态",
				dataIndex: "status",
				width: 10,
				render: (status, record) => (
					<Switch
						onChange={async current => {
							loadingListRef.current.push(record._id);
							setLoadingList([...loadingListRef.current]);
							try {
								await updateSource({ source: "role", id: record._id, status: current ? 1 : 0 });
								await fetchList();
								deleteLoadingItem(record._id);
								message.success(`${current ? "启用" : "禁用"}成功`);
							} catch (error) {
								deleteLoadingItem(record._id);
							}
						}}
						checked={status === 1}
						checkedChildren="启用"
						unCheckedChildren="禁用"
						loading={loadingList.find(item => item === record._id) !== undefined}
					/>
				),
			},
			{
				title: "角色头像",
				dataIndex: "avatar",
				width: 10,
				render: src => {
					if (!src) return null;
					return <Image src={`${REACT_APP_BASEURL}${src}`} width="36px" />;
				},
			},
			...getDateColumns<ColumnProps<RoleRecord>[]>().map(item => ({ ...item, width: 10 })),
			{
				title: "操作",
				width: 15,
				fixed: "right",
				render: (_, record) => (
					<>
						<Button onClick={() => { operatedRecord.current = record; setAuthVisible(true); }}>权限</Button>
						<Button
							type="primary"
							className="ml-2"
							onClick={() => {
								operatedRecord.current = record;
								setMode("edit");
								setInfoVisible(true);
								setTimeout(() => {
									formRef.current?.setFieldsValue({ ...record, status: !!record.status, avatar: record.avatar ? record.avatar : "" });
									record.avatar && uploadRef.current?.setUrl(`${REACT_APP_BASEURL}${record.avatar}`);
									!record.avatar && uploadRef.current?.setFileList([]);
								});
							}}
						>
							编辑
						</Button>
						<Popconfirm
							title={`确定删除${record.name}吗？`}
							onConfirm={async () => {
								await deleteSource({ source: "role", id: record._id });
								await fetchList();
								deleteLoadingItem(record._id);
								message.success("删除成功");
							}}
						>
							<Button className="ml-2" danger>
								删除
							</Button>
						</Popconfirm>
					</>
				),
			},
		],
		[loadingList]
	);
	return (
		<Table
			dataSource={list.map((item, key) => ({ ...item, key }))}
			columns={roleColumns}
			pagination={{
				...rolePageOptions,
				onChange(page, pageSize) {
					rolePageRef.current = page;
					rolePageSizeRef.current = pageSize;
					setRolePageOptions({ ...rolePageOptions, current: page, pageSize });
					fetchList();
				},
			}}
			scroll={{ x: 1480 }}
		/>
	);
};

export default forwardRef(RoleList);
